//
//  HomeViewController.m
//  meituan
//
//  Created by huiwenjiaoyu on 15/12/15.
//  Copyright © 2015年 Rick. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeTableView.h"
#import "CategoryModel.h"
#import <MapKit/MapKit.h>
#import "AFNetworking.h"
#import "DealModel.h"
#import "CityViewController.h"
#import "SearchViewController.h"
#import "WXRefresh.h"

@interface HomeViewController ()

@property (nonatomic, strong) HomeTableView *tableView;
@property (nonatomic, copy) NSArray *items;
@property (nonatomic, copy) NSArray *deals;
@property (nonatomic, copy) NSString *location;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalDeal;
@property (nonatomic, strong) NSNumber *cityId;

@end

@implementation HomeViewController

#pragma mark - 懒加载初始化

- (NSArray *)items
{
    if (_items == nil) {
        _items = [CategoryModel category];
    }
    return _items;
}


- (HomeTableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[HomeTableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
        _tableView.headInfos = self.items;
        __weak HomeViewController *weakSelf = self;
        [_tableView addPullDownRefreshBlock:^{
            weakSelf.currentPage += 1;
            if (weakSelf.currentPage >= weakSelf.totalDeal / 10) {
                weakSelf.currentPage = 1;
            }
            [weakSelf requsetDataWithLocation:weakSelf.location cityId:weakSelf.cityId page:weakSelf.currentPage];
        }];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    self.navigationController.navigationBar.translucent = NO;
    [super viewDidLoad];
    
    if (self.cityName.length == 0) {
        self.cityName = @"杭州";
        self.cityId = @600010000;
    }
    
    [self custmerNavigationBar];
    [self tableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:kLocateNotificationIdentifier object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(categorySelected:) name:kcategryNotificationIdentifier object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)categorySelected:(NSNotification *)notification
{
    
    NSNumber *number = notification.userInfo[@"controlTag"];
    NSString *name = notification.userInfo[@"name"];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.title = name;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -

#pragma mark - 加载用户附近的团单

- (void)reloadData:(NSNotification *)notification
{
    CLLocation *location = notification.userInfo[@"location"];
    NSString *locationStr = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];
    self.location = locationStr;
    self.currentPage = 1;
    [self requsetDataWithLocation:locationStr cityId:@600010000 page:self.currentPage];
}

- (void)requsetDataWithLocation:(NSString *)location cityId:(NSNumber *)cityId page:(NSInteger)page
{
    
    
    AFHTTPSessionManager *mananer = [AFHTTPSessionManager manager];
    [mananer.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
    
    [mananer GET:searchDeals
      parameters:@{
                   @"city_id":cityId,
                   @"cat_ids":@"326",
                   @"location":location,
                   @"page":@(page)
                   }
        progress:^(NSProgress * _Nonnull downloadProgress) {
            
            
        }
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [self.tableView.pullToRefreshView stopAnimating];
             if ([responseObject[@"errno"] integerValue] == 0) {
                 self.totalDeal = [[responseObject[@"data"] objectForKey:@"total"] integerValue];
                 NSArray *dealDics = [responseObject[@"data"] objectForKey:@"deals"];
                 self.deals = [DealModel dealsWithDic:dealDics];
                 //                 NSString *sortDes = [NSString stringWithFormat:@"self.ditance"];
                 NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
                 [self.deals sortedArrayUsingDescriptors:@[sort]];
                 self.tableView.deals = self.deals;
                 [self.tableView reloadData];
             }else {
                 
                 UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络加载错误,重新加载" preferredStyle:UIAlertControllerStyleAlert];
                 UIAlertAction *reload = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                     [self requsetDataWithLocation:location cityId:cityId page:4];//need to relocated
                 }];
                 
                 [alter addAction:reload];
                 [self presentViewController:alter animated:YES completion:nil];
             }
             
             
         }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
             
         }];
}
#pragma mark -

#pragma mark - 自定义navigationBar

- (void)setCityName:(NSString *)cityName
{
    if (![_cityName isEqualToString:cityName]) {
        
        _cityName = [cityName copy];
        for (UIView *view in self.navigationController.navigationBar.subviews) {
            
            if ([view isKindOfClass:[UIBarButtonItem class]]) {
                
                [view removeFromSuperview];
            }
        }
        [self custmerNavigationBar];
        
    }
}

- (void)setCity:(City *)city
{
    if (_city != city) {
        _city = city;
        self.cityName = _city.city_name;
        self.cityId = _city.city_id;
        self.currentPage = 1;
        [self requsetDataWithLocation:self.location cityId:_city.city_id page:self.currentPage];
    }
}

- (void)custmerNavigationBar
{
    //二维码
    UIButton *scan = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [scan addTarget:self action:@selector(scan:) forControlEvents:UIControlEventTouchUpInside];
    [scan setImage:[UIImage imageNamed:@"icon_homepage_scan_pressed"] forState:UIControlStateNormal];
    UIBarButtonItem *scanItem = [[UIBarButtonItem alloc] initWithCustomView:scan];
    //消息
    UIButton *tip = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [tip setImage:[UIImage imageNamed:@"icon_homepage_message_normal"] forState:UIControlStateNormal];
    [tip addTarget:self action:@selector(checkMessage:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *tipItem = [[UIBarButtonItem alloc] initWithCustomView:tip];
    
    self.navigationItem.rightBarButtonItems = @[tipItem,scanItem];
    //定位按钮
    UIButton *location = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
    [location addTarget:self action:@selector(showDistrictList:) forControlEvents:UIControlEventTouchUpInside];
    [location setTitle:[self.cityName substringToIndex:2] forState:UIControlStateNormal];
    [location setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [location setImage:[UIImage imageNamed:@"arrow_down"] forState:UIControlStateNormal];
    UIBarButtonItem *locationItem = [[UIBarButtonItem alloc] initWithCustomView:location];
    //搜索
    UIButton *search = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - CGRectGetWidth(scan.frame) * 5.5, 30)];
    [search addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"background_home_searchBar"];
    image = [image stretchableImageWithLeftCapWidth:15 topCapHeight:15];
    [search setBackgroundImage:image forState:UIControlStateNormal];
    [search setTitle:@"🔍搜索商家或地点" forState:UIControlStateNormal];
    [search setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItems = @[locationItem,[[UIBarButtonItem alloc] initWithCustomView:search]];
    
}

- (void)checkMessage:(UIButton *)btn
{
    NSLog(@"check message");
}

- (void)scan:(UIButton *)btn
{
    NSLog(@"scan");
}

- (void)showDistrictList:(UIButton *)btn
{
    
    CityViewController *vc = [[CityViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)search:(UIButton *)btn
{
    SearchViewController *vc = [[SearchViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}


@end
